package com.aceitunaproject.server;

import java.io.Serializable;
import java.nio.ByteBuffer;

import com.aceitunaproject.server.player.Player;
import com.aceitunaproject.shared.message.Message;
import com.aceitunaproject.shared.message.MessageConstants;
import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.ClientSessionListener;
import com.sun.sgs.app.ManagedReference;


/**
 * A concrete, package-private class that enforces the proxy pattern for
 * incoming messages. Instances are created for a given {@code UserPlayer},
 * and that {@code UserPlayer}'s current {@code GameProxy} is used to
 * handle incoming messages. The {@code UserPlayer} is notified on logout.
 * @author Federico Bergstein
 *
 */
final class PlayerListener implements ClientSessionListener, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1297180090980195374L;

	// the user player sending us messages
    private final ManagedReference<? extends Player> playerRef;

    /** Create an instance of {@code UserListener} for the given player. */
    PlayerListener(Player player) {
        playerRef = AppContext.getDataManager().createReference(player);
    }
    
    /** {@inheritDoc} */
    public void receivedMessage(ByteBuffer message) {
        Player player = playerRef.get();
      
        int messageType = message.get();
		if (messageType == MessageConstants.TYPE_BINARY) {
			AceitunaContext.getMessageHandler()
					.handleBinaryMessage(player, message.asReadOnlyBuffer());
		} else {
			byte[] buffer = new byte[message.remaining()];
			message.get(buffer);

			Message deserializedMessage = (Message) ServerConfiguration
					.getObjectSerializer().deserialize(buffer);
			AceitunaContext.getMessageHandler().handleObjectMessage(player, deserializedMessage);
		}
    }

    /** {@inheritDoc} */
    public void disconnected(boolean graceful) {
        Player player = playerRef.getForUpdate();
        player.setSession(null);
    }


}
